import wave
import os
import numpy as np
from pydub import AudioSegment
import matplotlib.pylab as plt
def getOneWave(wav_file):
    with wave.open(wav_file ,'rb') as f:
        params = f.getparams()
        #print(params)
        nchannels, sampwidth, framerate, nframes = params[:4]
        nframes = int(nframes/80)
        strData = f.readframes(nframes)
        waveData = np.frombuffer(strData,dtype=np.int32)
        waveData = waveData*1.0/(np.max(waveData))  # 幅值归一化
        #print(nchannels,sampwidth,framerate,nframes)
        # plot the wave
        time = np.arange(0,nframes)*(1.0 / framerate)
#        plt.figure(figsize=(100,2))
        plt.plot(time,waveData)
        plt.xlabel("Time(s)")
        plt.ylabel("Amplitude")
        plt.title("Single channel wavedata")
        plt.show()
        ave=0
        absave=0
        for item in waveData:
            if item!=0:
                ave+=item
                absave+=abs(item)
        ave=ave/nframes
        absave=absave/nframes
        squ=0
        for item in waveData:
            if item != 0:
                squ+=(ave-item)**2
        squ=squ/nframes
        #print(absave,squ)
        return absave,squ,nframes
def write(thePath,data,dim=2,gap=','):
    '''

    :param thePath:
    :param data:二维数组
    :return:
    '''
    if dim==2:
        with open(thePath, 'w', encoding='utf-8') as f:
            length=data.__len__()
            for i in range(length):
                line=[str(x) for x in data[i]]
                f.writelines(gap.join(line))
                if i!=length-1:
                    f.writelines("\n")
    if dim==1:
        with open(thePath, 'w', encoding='utf-8') as f:
            data=[str(x) for x in data]
            f.writelines(gap.join(data))
    return True
def progressBar(time,times,prompt="已完成："):
    now=round((time + 1) * 100 / times,2)
    print('\r' + prompt + str(now), end='%', flush=True)
def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print("-----------")
        print(root)   #os.walk()所在目录
        print(dirs)   #os.walk()所在目录的所有目录名
        print(files)   #os.walk()所在目录的所有非目录文件名
        print(" ")
        return files
if __name__ == '__main__':
    #配置ffmpeg环境变量（先下载）
    os.environ['path'] = os.environ.get('path')+';D:\\迅雷下载\\ffmpeg-20200628-4cfcfb3-win64-static\\ffmpeg-20200628-4cfcfb3-win64-static\\bin'
    root='D:\大二下\数据科学\带作业\差榜\\add'
    files=file_name(root)
    for i in range(files.__len__()):
        wav_file=root+'\\'+str(i+501)+'.wav'
        sound = AudioSegment.from_mp3(root+'\\'+files[i])
        sound.export(wav_file, format='wav')
        progressBar(i,files.__len__())
    #write(root+'\\'+'wave.csv',data)



